package com.example.demo;

import com.immer.session.RedisSessionClient;
import com.immer.session.RedisSessionManger;
import com.immer.session.SessionClusterFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

@SpringBootApplication
@RestController
public class SessionApplication {

    public static void main(String[] args) {
        SpringApplication.run(SessionApplication.class, args);
    }

    @RequestMapping("/hello")
    public String helloWorld(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("wei",123);
        Enumeration<String> enumeration = session.getAttributeNames();
        while (enumeration.hasMoreElements()){
            String attrName=  enumeration.nextElement();
            System.out.println("attrName:" + attrName +"attrValue:" + session.getAttribute(attrName));
        }
        return "Hello Spring-session";
    }

    @RequestMapping("/expire")
    public String expireSession(HttpSession  session) {
        System.out.println(session.getServletContext());
        session.invalidate();
        return "Hello Spring-session";
    }

    @Bean
    public RedisSessionManger redisSessionClient(RedisTemplate redisTemplate){
        return new RedisSessionManger(new RedisSessionClient(redisTemplate));
    }
    @Bean
    public FilterRegistrationBean testFilterRegistration(RedisSessionManger redisSessionManger) {
        FilterRegistrationBean registration = new FilterRegistrationBean(new SessionClusterFilter(redisSessionManger));
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("sessionFilter");
        return registration;
    }

}

